package com.code;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import com.Global.Global;
import com.database.DBSystem;
import com.example.R;
import com.object.obShipReceipt;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;


public class TK_NhapXuat extends Activity{
	private DBSystem dbHelper;
	LinearLayout llMain;
	private final int REQUESTSHIPRECEIPT = 100;
	private String QUERY_STORE_NHAPXUAT;
	private int chooseNhapXuat;
	private String strNhomChon = "" ,strKhoChon = "";
	ArrayList<Integer> date_actual ;
	private TableRow rowFocus;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tk_nhapxuat);
		
		chooseNhapXuat = super.getIntent().getExtras().getInt("choose_mau");
		strNhomChon = super.getIntent().getExtras().getString("strNhomChon");
		strKhoChon = super.getIntent().getExtras().getString("strKhoChon");
		date_actual =super.getIntent().getExtras().getIntegerArrayList("date_actual");
		String date = String.valueOf(date_actual.get(2))+DetailCuocGoi.setMonth(date_actual.get(1))+Global.formatDay(date_actual.get(0));
		if(chooseNhapXuat == TK_ChonMau.CHOOSE_XUAT)
			QUERY_STORE_NHAPXUAT = "spMobileBaoCaoChiTietXuatHang '"+date+"','"+date+"','"+strKhoChon+"','"+strNhomChon+"'";
		else
			QUERY_STORE_NHAPXUAT = "spMobileBaoCaoChiTietNhapHang '"+date+"','"+date+"','"+strKhoChon+"','"+strNhomChon+"'";
		
		// declare component
		llMain = (LinearLayout) findViewById(R.id.llMain);
		selectAllDetailShipReceipt();
	}	
	/**
	 * @author trangbm
	 * @return 
	 * date 17/03/2014
	 */
	public Boolean selectAllDetailShipReceipt()
	{
		Connection conn = null;
		try{
			String driver = "net.sourceforge.jtds.jdbc.Driver";
			Class.forName(driver).newInstance();

			dbHelper = new DBSystem(this);
			dbHelper.open();
			Cursor cur = dbHelper.SelectSystemAll();
			String strServerName = "";
			String strServerPort = "";
			String strLogin = "";
			String strPassword = "";
			String strDatabaseName = "";
			if (cur != null) {
				while (cur.moveToNext()) {
					strServerName = cur.getString(1).toString();
					strServerPort = cur.getString(2).toString();
					strLogin = cur.getString(3).toString();
					strPassword = cur.getString(4).toString();
					strDatabaseName = cur.getString(5).toString();
				}
			}

			String url = "jdbc:jtds:sqlserver://" + strServerName + ":"
					+ strServerPort + ";DatabaseName=" + strDatabaseName
					+ ";integratedSecurity=true;user=" + strLogin
					+ ";password=" + strPassword + "";
			conn = DriverManager.getConnection(url);
			PreparedStatement stmt = conn
					.prepareStatement(QUERY_STORE_NHAPXUAT);
			stmt.execute();
			ResultSet rs = stmt.getResultSet();
			loadData(rs);
			stmt.close();
			conn.close();
			return true;
		}catch(Exception ex)
		{
			return false;
		}	
	}

	public void loadData(final ResultSet rs) throws SQLException
	{//load date edit by trangbm date 15/03
		Float total = 0.0f;
		Integer totalSL = 0;
		final TableLayout table =  new TableLayout(this);
		llMain.addView(table);
		TableRow trHead = new TableRow(this);
		trHead.setWeightSum(5.0f);
		
		TextView tvTenHang = new TextView(this);
		tvTenHang.setText("Mã hàng");
		TK_TongMatHang.setLayoutForTextView(tvTenHang, true, Gravity.CENTER, 10,2.5f);

		TextView tvSoLuong = new TextView(this);
		tvSoLuong.setText("SL");
		TK_TongMatHang.setLayoutForTextView(tvSoLuong, true, Gravity.CENTER, 10,0.5f);

		TextView tvDongia = new TextView(this);
		tvDongia.setText("Đơn giá");
		TK_TongMatHang.setLayoutForTextView(tvDongia, true, Gravity.CENTER, 10,1.0f);
		
		TextView tvThanhTien = new TextView(this);
		tvThanhTien.setText("TT");
		TK_TongMatHang.setLayoutForTextView(tvThanhTien, true, Gravity.CENTER, 10,1.0f,true);
		
		trHead.addView(tvTenHang);
		trHead.addView(tvSoLuong);
		trHead.addView(tvDongia);
		trHead.addView(tvThanhTien);
		table.addView(trHead);
	
		try {
			while(rs.next())
			{
				final obShipReceipt shipReciept = new obShipReceipt();
				if(rs.getString("Product Name") != null)
					shipReciept.setProductName(rs.getString("Product Name").toString());
				if(rs.getString("SL") != null)
				{
					shipReciept.setQuantity(String.valueOf(rs.getInt("SL")));
					totalSL = totalSL + rs.getInt("SL");
				}
				if(rs.getString("dongia") != null)
					shipReciept.setPriceActual(rs.getString("dongia"));			
				if(rs.getString("Tennguoimua") !=null)
					shipReciept.setNameBpartner(rs.getString("Tennguoimua").toString());
				if(rs.getString("Diachigiaohang") != null)
					shipReciept.setAddress(rs.getString("Diachigiaohang").toString());
				if(rs.getString("DTDD") != null)
					shipReciept.setPhone(rs.getString("DTDD").toString());
				if(rs.getString("DDBH") != null)
					shipReciept.setEmployee(rs.getString("DDBH").toString());
				if(rs.getString("ThanhTien") != null){
					shipReciept.setThanhTien(rs.getString("ThanhTien"));
					total = total + Float.valueOf(rs.getString("ThanhTien"));
				}
				else
					shipReciept.setThanhTien("0");
				TableRow tr = new TableRow(this);
				// convert color while on click
				tr.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						try {
							if (rowFocus != null)
								rowFocus.setBackgroundColor(Color.TRANSPARENT);
							rowFocus = (TableRow) v;
							v.setBackgroundColor(Color.YELLOW);
						} catch (Exception e) {
						}
					}
				});
				
				tr.setOnLongClickListener(new OnLongClickListener() {
					public boolean onLongClick(View v) {
						ArrayList<String> detail = new ArrayList<String>();
						detail.add(0, shipReciept.getNameBpartner());
						detail.add(1, shipReciept.getAddress());
						detail.add(2, shipReciept.getPhone());
						detail.add(3, shipReciept.getEmployee());
						detail.add(4, Global.formatCurrency(shipReciept.getThanhTien()));
						if (!shipReciept.getNameBpartner().equals("")) {
							Intent i = new Intent(TK_NhapXuat.this,
									DetailShipReceipt.class);
							Bundle b = new Bundle();
							b.putStringArrayList("detailshipreceipt", detail);
							b.putInt("chooseNhapXuat",chooseNhapXuat);
							i.putExtras(b);
							startActivityForResult(i, REQUESTSHIPRECEIPT);
						}
						// TODO Auto-generated method stub
						return false;
					}					
				});
				tr.setWeightSum(5.0f);
				
				TextView tvTenHangs = new TextView(this);
				tvTenHangs.setText(shipReciept.getProductName());
				TK_TongMatHang.setLayoutForTextView(tvTenHangs, false, Gravity.LEFT, 10,2.5f);
				if(rs.isLast())
					tvTenHangs.setBackgroundResource(R.layout.border_topleftbottom);

				TextView tvSoLuongs = new TextView(this);
				tvSoLuongs.setText(shipReciept.getQuantity());
				TK_TongMatHang.setLayoutForTextView(tvSoLuongs, false, Gravity.CENTER, 10,0.5f);
				if(rs.isLast())
					tvSoLuongs.setBackgroundResource(R.layout.border_topleftbottom);

				TextView tvDongias = new TextView(this);
				tvDongias.setText(Global.formatDecimal(Float.valueOf(shipReciept.getPriceActual())));
				TK_TongMatHang.setLayoutForTextView(tvDongias, false, Gravity.RIGHT, 10,1.0f,true);
//				tvDongias.setGravity(Gravity.RIGHT);
				if(rs.isLast())
					tvDongias.setBackgroundResource(R.layout.border_topleftbottom);
				
				TextView tvThanhTiens = new TextView(this);
				tvThanhTiens.setText(Global.formatDecimal(Float.valueOf(shipReciept.getThanhTien())));
				TK_TongMatHang.setLayoutForTextView(tvThanhTiens, false, Gravity.RIGHT, 10,1.0f,true);
				tvThanhTiens.setBackgroundResource(R.layout.border);			
				
				tr.addView(tvTenHangs);
				tr.addView(tvSoLuongs);
				tr.addView(tvDongias);
				tr.addView(tvThanhTiens);
				table.addView(tr);

			}
			//Row Calculator total 
			TableRow tREnd = new TableRow(this);
			tREnd.setWeightSum(5.0f);
			
			TextView tvTenHangEnd = new TextView(this);
			tvTenHangEnd.setText("Số lượng tổng");
			TK_TongMatHang.setLayoutForTextView(tvTenHangEnd, true, Gravity.CENTER, 10,2.5f);
			tvTenHangEnd.setBackgroundResource(R.layout.border_topleftbottom);
			
			TextView tvSoLuongEnd = new TextView(this);
			tvSoLuongEnd.setText(totalSL.toString());
			TK_TongMatHang.setLayoutForTextView(tvSoLuongEnd,true, Gravity.CENTER, 10,0.5f);
			tvSoLuongEnd.setBackgroundResource(R.layout.border_topleftbottom);

			TextView tvDongiaEnd = new TextView(this);
			tvDongiaEnd.setText("Tổng tiền");
			TK_TongMatHang.setLayoutForTextView(tvDongiaEnd, true, Gravity.CENTER, 10,1.0f);
			tvDongiaEnd.setBackgroundResource(R.layout.border_topleftbottom);
			
			TextView tvThanhTienEnd = new TextView(this);
			tvThanhTienEnd.setText(Global.formatDecimal(total));
			TK_TongMatHang.setLayoutForTextView(tvThanhTienEnd, true, Gravity.RIGHT, 10,1.0f,true);
			tvThanhTienEnd.setBackgroundResource(R.layout.border);
//			tvThanhTienEnd.setGravity(Gravity.RIGHT);
			
			tREnd.addView(tvTenHangEnd);
			tREnd.addView(tvSoLuongEnd);
			tREnd.addView(tvDongiaEnd);
			tREnd.addView(tvThanhTienEnd);
			table.addView(tREnd);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void setLayoutForTextView(TextView tv, Boolean isBold, int gravity, int Width) {
		LayoutParams params = new TableRow.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		params.weight = 1.0f;
		tv.setLayoutParams(params);
		tv.setBackgroundResource(R.layout.border_topleft);
		tv.setPadding(2, 10, 2, 10);
		tv.setGravity(gravity);
		tv.setWidth(Width);
		tv.setTextSize(20);

		if (isBold)
			tv.setTypeface(null, Typeface.BOLD);
	}
}
